package br.ufrj.neg.evento.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.velocity.tools.view.VelocityViewServlet;

import br.ufrj.neg.bean.Idioma;
import br.ufrj.neg.constants.General;
import br.ufrj.neg.evento.bean.ArtefatoBean;
import br.ufrj.neg.evento.model.ArtefatoModel;

public class DownloadArtefatoEventoAction extends VelocityViewServlet {

	private static final long serialVersionUID = 1L;

	// private static Logger log = Logger.getLogger("rootLogger");

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		
		try {
				/*
			 * Pega os parametros passados
			 */
			String indArtefato = request.getParameter("idArtefato");
			Idioma idioma = (Idioma) request.getAttribute("idioma");
			ArtefatoBean ab = new ArtefatoBean(idioma);
			ab.setId(Integer.parseInt(indArtefato));
			
			ArtefatoModel am = new ArtefatoModel(); 
			ab = am.getArtefato(ab);

			if( ab.getTipoArtefato() == 1 ){
				response.setContentType("application/pdf");
			}
			else if(ab.getTipoArtefato() == 2 ){
				response.setContentType("application/doc");
			}
			else if(ab.getTipoArtefato() == 3 ){
				response.setContentType("application/ppt");
			}
			else if(ab.getTipoArtefato() == 4 ){
				response.setContentType("application/xsl");
			}
			else if(ab.getTipoArtefato() == 5 ){
				response.setContentType("application/project");
			}
			else if(ab.getTipoArtefato() == 6 ){
				response.setContentType("image/jpg");
			}
			else{
				response.setContentType("application/octet-stream");
			}
			
			
			response.setHeader("Content-Disposition", "attachment;filename="
					+ ab.getNome());

			// OutputStream os
			ServletOutputStream outputStream = response.getOutputStream();
			response.setContentLength(ab.getArquivoAsByte().length);
			outputStream.write(ab.getArquivoAsByte());
			outputStream.flush();
			outputStream.close();

		} catch (Exception e) {
			System.out.println(e);
			request.getRequestDispatcher(General.TELA_ERRO_500).forward(request,
					response);
		}
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
	
		doPost(request,response);
		
	
	}

}
